﻿/*
* Copyright (c) 2010-2012 Tesla Engine Group
* 
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* 
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* 
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/


using System;
using Tesla.Content;
using Tesla.Core;
using Tesla.Graphics.Implementation;
using Tesla.Util;

namespace Tesla.Graphics {
    /// <summary>
    /// Represents a 3-Dimensional texture that has width, height, and depth.
    /// </summary>
    public class Texture3D : Texture {
        private Texture3DImplementation _impl;

        /// <summary>
        /// Gets the API-specific implementation of this resource.
        /// </summary>
        public override GraphicsResourceImplementation Implementation {
            get {
                return _impl;
            }
        }

        /// <summary>
        /// Gets the format of the texture resource.
        /// </summary>
        public override SurfaceFormat Format {
            get {
                return _impl.Format;
            }
        }

        /// <summary>
        /// Gets the number of mip map levels in the texture resource.
        /// </summary>
        public override int MipCount {
            get {
                return _impl.MipCount;
            }
        }

        /// <summary>
        /// Gets the texture dimensions, identifying the texture resource.
        /// </summary>
        public override TextureDimensions Dimensions {
            get {
                return TextureDimensions.Three;
            }
        }

        /// <summary>
        /// Gets the texture width, in pixels.
        /// </summary>
        public int Width {
            get {
                return _impl.Width;
            }
        }

        /// <summary>
        /// Gets the texture height, in pixels.
        /// </summary>
        public int Height {
            get {
                return _impl.Height;
            }
        }

        /// <summary>
        /// Gets the texture depth, in pixels.
        /// </summary>
        public int Depth {
            get {
                return _impl.Depth;
            }
        }

        /// <summary>
        /// For ISavable.
        /// </summary>
        protected Texture3D() {}

        /// <summary>
        /// Creates a new instance of <see cref="Texture3D"/>. This creates an empty texture.
        /// </summary>
        /// <param name="width">The width of the texture in pixels.</param>
        /// <param name="height">The height of the texture in pixels.</param>
        /// <param name="depth">The depth of the texture in pixels.</param>
        /// <exception cref="Tesla.Core.TeslaException">Thrown if creating the underlying texture fails or the render
        /// system was not initialized.</exception>
        public Texture3D(int width, int height, int depth) {
            IRenderSystemProvider renderSystem = Engine.Services.GetService<IRenderSystemProvider>();
            if(renderSystem == null) {
                Dispose();
                throw new TeslaException("Render system provider not set, cannot create graphics resource implementation.");
            }

            base.RenderSystem = renderSystem;

            try {
                _impl = renderSystem.CreateTexture3DImplementation(width, height, depth, false, SurfaceFormat.Color, null);
            } catch(Exception e) {
                Dispose();
                throw new TeslaException("Error creating underlying implementation, see inner exception for details.", e);
            }
        }

        /// <summary>
        /// Creates a new instance of <see cref="Texture3D"/>. This creates an empty texture.
        /// </summary>
        /// <param name="width">The width of the texture in pixels.</param>
        /// <param name="height">The height of the texture in pixels.</param>
        /// <param name="depth">The depth of the texture in pixels.</param>
        /// <param name="genMipMap">Whether or not mip maps should be generated. If so, the levels are created.</param>
        /// <param name="format">The surface format.</param>
        /// <exception cref="Tesla.Core.TeslaException">Thrown if creating the underlying texture fails or the render
        /// system was not initialized.</exception>
        public Texture3D(int width, int height, int depth, bool genMipMap, SurfaceFormat format) {
            IRenderSystemProvider renderSystem = Engine.Services.GetService<IRenderSystemProvider>();
            if(renderSystem == null) {
                Dispose();
                throw new TeslaException("Render system provider not set, cannot create graphics resource implementation.");
            }

            base.RenderSystem = renderSystem;

            try {
                _impl = renderSystem.CreateTexture3DImplementation(width, height, depth, genMipMap, format, null);
            } catch(Exception e) {
                Dispose();
                throw new TeslaException("Error creating underlying implementation, see inner exception for details.", e);
            }
        }

        /// <summary>
        /// Creates a new instance of <see cref="Texture3D"/>.
        /// </summary>
        /// <param name="width">The width of the texture in pixels.</param>
        /// <param name="height">The height of the texture in pixels.</param>
        /// <param name="depth">The depth of the texture in pixels.</param>
        /// <param name="genMipMap">Whether or not mip maps should be generated. If so, the levels are created.</param>
        /// <param name="format">The surface format.</param>
        /// <param name="initialData">The data to initialize the first mip level to.</param>
        /// <exception cref="Tesla.Core.TeslaException">Thrown if creating the underlying texture fails or the render
        /// system was not initialized.</exception>
        public Texture3D(int width, int height, int depth, bool genMipMap, SurfaceFormat format, DataBuffer initialData) {
            IRenderSystemProvider renderSystem = Engine.Services.GetService<IRenderSystemProvider>();
            if(renderSystem == null) {
                Dispose();
                throw new TeslaException("Render system provider not set, cannot create graphics resource implementation.");
            }

            base.RenderSystem = renderSystem;

            try {
                _impl = renderSystem.CreateTexture3DImplementation(width, height, depth, genMipMap, format, initialData);
            } catch(Exception e) {
                Dispose();
                throw new TeslaException("Error creating underlying implementation, see inner exception for details.", e);
            }
        }

        /// <summary>
        /// Creates a new instance of <see cref="Texture3D"/>. This creates an empty texture.
        /// </summary>
        /// <param name="renderSystem">Render system used to create the underlying implementation.</param>
        /// <param name="width">The width of the texture in pixels.</param>
        /// <param name="height">The height of the texture in pixels.</param>
        /// <param name="depth">The depth of the texture in pixels.</param>
        /// <exception cref="Tesla.Core.TeslaException">Thrown if creating the underlying texture fails or the render
        /// system was not initialized.</exception>
        public Texture3D(IRenderSystemProvider renderSystem, int width, int height, int depth) {
            if(renderSystem == null) {
                Dispose();
                throw new TeslaException("Render system provider not set, cannot create graphics resource implementation.");
            }

            base.RenderSystem = renderSystem;

            try {
                _impl = renderSystem.CreateTexture3DImplementation(width, height, depth, false, SurfaceFormat.Color, null);
            } catch(Exception e) {
                Dispose();
                throw new TeslaException("Error creating underlying implementation, see inner exception for details.", e);
            }
        }

        /// <summary>
        /// Creates a new instance of <see cref="Texture3D"/>. This creates an empty texture.
        /// </summary>
        /// <param name="renderSystem">Render system used to create the underlying implementation.</param>
        /// <param name="width">The width of the texture in pixels.</param>
        /// <param name="height">The height of the texture in pixels.</param>
        /// <param name="depth">The depth of the texture in pixels.</param>
        /// <param name="genMipMap">Whether or not mip maps should be generated. If so, the levels are created.</param>
        /// <param name="format">The surface format.</param>
        /// <exception cref="Tesla.Core.TeslaException">Thrown if creating the underlying texture fails or the render
        /// system was not initialized.</exception>
        public Texture3D(IRenderSystemProvider renderSystem, int width, int height, int depth, bool genMipMap, SurfaceFormat format) {
            if(renderSystem == null) {
                Dispose();
                throw new TeslaException("Render system provider not set, cannot create graphics resource implementation.");
            }

            base.RenderSystem = renderSystem;

            try {
                _impl = renderSystem.CreateTexture3DImplementation(width, height, depth, genMipMap, format, null);
            } catch(Exception e) {
                Dispose();
                throw new TeslaException("Error creating underlying implementation, see inner exception for details.", e);
            }
        }

        /// <summary>
        /// Creates a new instance of <see cref="Texture3D"/>.
        /// </summary>
        /// <param name="renderSystem">Render system used to create the underlying implementation.</param>
        /// <param name="width">The width of the texture in pixels.</param>
        /// <param name="height">The height of the texture in pixels.</param>
        /// <param name="depth">The depth of the texture in pixels.</param>
        /// <param name="genMipMap">Whether or not mip maps should be generated. If so, the levels are created.</param>
        /// <param name="format">The surface format.</param>
        /// <param name="initialData">The data to initialize the first mip level to.</param>
        /// <exception cref="Tesla.Core.TeslaException">Thrown if creating the underlying texture fails or the render
        /// system was not initialized.</exception>
        public Texture3D(IRenderSystemProvider renderSystem, int width, int height, int depth, bool genMipMap, SurfaceFormat format, DataBuffer initialData) {
            if(renderSystem == null) {
                Dispose();
                throw new TeslaException("Render system provider not set, cannot create graphics resource implementation.");
            }

            base.RenderSystem = renderSystem;

            try {
                _impl = renderSystem.CreateTexture3DImplementation(width, height, depth, genMipMap, format, initialData);
            } catch(Exception e) {
                Dispose();
                throw new TeslaException("Error creating underlying implementation, see inner exception for details.", e);
            }
        }

        /// <summary>
        /// Releases unmanaged resources and performs other cleanup operations before the
        /// <see cref="Texture3D"/> is reclaimed by garbage collection.
        /// </summary>
        ~Texture3D() {
            Dispose(false);
        }

        /// <summary>
        /// Gets the data from the texture.
        /// </summary>
        /// <typeparam name="T">Type of data in the array</typeparam>
        /// <param name="data">The array of data</param>
        /// <exception cref="System.ArgumentNullException">Thrown if data is null.</exception>
        /// <exception cref="Tesla.Core.TeslaException">Thrown if there is an error reading from the texture
        /// or arguments are invalid, check the inner exception for additional details.</exception>
        /// <remarks>See implementors for details on other exceptions that can be thrown.</remarks>
        public void GetData<T>(T[] data) where T : struct {
            if(data == null || data.Length == 0) {
                throw new ArgumentNullException("Data cannot be null.");
            }

            try {
                _impl.GetData<T>(data, 0, 0, _impl.Width, 0, _impl.Height, 0, _impl.Depth, 0, data.Length);
            } catch(Exception e) {
                throw new TeslaException("Error writing to texture: \n" + e.Message, e);
            }
        }

        /// <summary>
        /// Gets the data from the texture.
        /// </summary>
        /// <typeparam name="T">Type of data in the array</typeparam>
        /// <param name="data">The array of data</param>
        /// <param name="startIndex">Starting index in the array to start reading from.</param>
        /// <param name="elementCount">Number of elements to write.</param>
        /// <exception cref="System.ArgumentNullException">Thrown if data is null.</exception>
        /// <exception cref="Tesla.Core.TeslaException">Thrown if there is an error reading from the texture
        /// or arguments are invalid, check the inner exception for additional details.</exception>
        /// <remarks>See implementors for details on other exceptions that can be thrown.</remarks>
        public void GetData<T>(T[] data, int startIndex, int elementCount) where T : struct {
            if(data == null || data.Length == 0) {
                throw new ArgumentNullException("Data cannot be null.");
            }

            try {
                _impl.GetData<T>(data, 0, 0, _impl.Width, 0, _impl.Height, 0, _impl.Depth, startIndex, elementCount);
            } catch(Exception e) {
                throw new TeslaException("Error writing to texture: \n" + e.Message, e);
            }
        }

        /// <summary>
        /// Gets the data from the texture.
        /// </summary>
        /// <typeparam name="T">Type of data in the array</typeparam>
        /// <param name="data">The array of data</param>
        /// <param name="mipLevel">Mip map level to read from</param>
        /// <param name="left">Left-most width position in the texture at which to acess. (0 or greater)</param>
        /// <param name="right">Right-most width position in the texture at which to acess. (width or less)</param>
        /// <param name="top">Top-most height position in the texture at which to acess. (0 or greater)</param>
        /// <param name="bottom">Bottom-most height position in the texture at which to acess. (height or less)</param>
        /// <param name="front">Front-most depth position in the texture at which to acess. (0 or greater)</param>
        /// <param name="back">Back-most depth position in the texture at which to acess. (depth or less)</param>
        /// <param name="startIndex">Starting index in the array to start reading from.</param>
        /// <param name="elementCount">Number of elements to write.</param>
        /// <exception cref="System.ArgumentNullException">Thrown if data is null.</exception>
        /// <exception cref="Tesla.Core.TeslaException">Thrown if there is an error reading from the texture
        /// or arguments are invalid, check the inner exception for additional details.</exception>
        /// <remarks>See implementors for details on other exceptions that can be thrown.</remarks>
        public void GetData<T>(T[] data, int mipLevel, int left, int right, int top, int bottom, int front, int back, int startIndex, int elementCount) where T : struct {
            if(data == null || data.Length == 0) {
                throw new ArgumentNullException("Data cannot be null.");
            }

            try {
                _impl.GetData<T>(data, mipLevel, left, right, top, bottom, front, back, startIndex, elementCount);
            } catch(Exception e) {
                throw new TeslaException("Error writing to texture: \n" + e.Message, e);
            }
        }

        /// <summary>
        /// Sets the data from the texture.
        /// </summary>
        /// <typeparam name="T">Type of data in the array</typeparam>
        /// <param name="data">The array of data</param>
        /// <exception cref="System.ArgumentNullException">Thrown if data is null.</exception>
        /// <exception cref="Tesla.Core.TeslaException">Thrown if there is an error writing to the texture
        /// or arguments are invalid, check the inner exception for additional details.</exception>
        /// <remarks>See implementors for details on other exceptions that can be thrown.</remarks>
        public void SetData<T>(T[] data) where T : struct {
            if(data == null || data.Length == 0) {
                throw new ArgumentNullException("Data cannot be null.");
            }

            try {
                _impl.SetData<T>(data, 0, 0, _impl.Width, 0, _impl.Height, 0, _impl.Depth, 0, data.Length);
            } catch(Exception e) {
                throw new TeslaException("Error writing to texture: \n" + e.Message, e);
            }
        }

        /// <summary>
        /// Sets the data from the texture.
        /// </summary>
        /// <typeparam name="T">Type of data in the array</typeparam>
        /// <param name="data">The array of data</param>
        /// <param name="startIndex">Starting index in the array to start reading from.</param>
        /// <param name="elementCount">Number of elements to write.</param>
        /// <exception cref="System.ArgumentNullException">Thrown if data is null.</exception>
        /// <exception cref="Tesla.Core.TeslaException">Thrown if there is an error writing to the texture
        /// or arguments are invalid, check the inner exception for additional details.</exception>
        /// <remarks>See implementors for details on other exceptions that can be thrown.</remarks>
        public void SetData<T>(T[] data, int startIndex, int elementCount) where T : struct {
            if(data == null || data.Length == 0) {
                throw new ArgumentNullException("Data cannot be null.");
            }

            try {
                _impl.SetData<T>(data, 0, 0, _impl.Width, 0, _impl.Height, 0, _impl.Depth, startIndex, elementCount);
            } catch(Exception e) {
                throw new TeslaException("Error writing to texture: \n" + e.Message, e);
            }
        }

        /// <summary>
        /// Sets the data from the texture.
        /// </summary>
        /// <typeparam name="T">Type of data in the array</typeparam>
        /// <param name="data">The array of data</param>
        /// <param name="mipLevel">Mip map level to read from</param>
        /// <param name="left">Left-most width position in the texture at which to acess. (0 or greater)</param>
        /// <param name="right">Right-most width position in the texture at which to acess. (width or less)</param>
        /// <param name="top">Top-most height position in the texture at which to acess. (0 or greater)</param>
        /// <param name="bottom">Bottom-most height position in the texture at which to acess. (height or less)</param>
        /// <param name="front">Front-most depth position in the texture at which to acess. (0 or greater)</param>
        /// <param name="back">Back-most depth position in the texture at which to acess. (depth or less)</param>
        /// <param name="startIndex">Starting index in the array to start reading from.</param>
        /// <param name="elementCount">Number of elements to write.</param>
        /// <exception cref="System.ArgumentNullException">Thrown if data is null.</exception>
        /// <exception cref="Tesla.Core.TeslaException">Thrown if there is an error writing to the texture
        /// or arguments are invalid, check the inner exception for additional details.</exception>
        /// <remarks>See implementors for details on other exceptions that can be thrown.</remarks>
        public void SetData<T>(T[] data, int mipLevel, int left, int right, int top, int bottom, int front, int back, int startIndex, int elementCount) where T : struct {
            if(data == null || data.Length == 0) {
                throw new ArgumentNullException("Data cannot be null.");
            }

            try {
                _impl.SetData<T>(data, mipLevel, left, right, top, bottom, front, back, startIndex, elementCount);
            } catch(Exception e) {
                throw new TeslaException("Error writing to texture: \n" + e.Message, e);
            }
        }


        /// <summary>
        /// Serializes the object and writes it to the output.
        /// </summary>
        /// <param name="output">Savable Output</param>
        public override void Write(ISavableWriter output) {
            SurfaceFormat format = _impl.Format;
            int width = _impl.Width;
            int height = _impl.Height;
            int depth = _impl.Depth;
            int mipCount = _impl.MipCount;

            output.Write("Name", _impl.Name);
            output.WriteEnum<SurfaceFormat>("Format", format);
            output.Write("Width", width);
            output.Write("Height", height);
            output.Write("Depth", depth);
            output.Write("MipCount", mipCount);

            int width2 = width;
            int height2 = height;
            int depth2 = depth;

            for(int i = 0; i < mipCount; i++) {
                byte[] byteBuffer = new byte[MemoryHelper.CalculateMipSize(width, height, depth, i, format)];
                _impl.GetData<byte>(byteBuffer, i, 0, width2, 0, height2, 0, depth2, 0, byteBuffer.Length);
                width2 = System.Math.Max(width2 >> 1, 1);
                height2 = System.Math.Max(height2 >> 1, 1);
                depth2 = System.Math.Max(depth2 >> 1, 1);
                output.Write(String.Format("MipLevel{0}", i.ToString()), byteBuffer);
            }
        }

        /// <summary>
        /// Deserializes the object and populates it from the input.
        /// </summary>
        /// <param name="input">Savable input</param>
        /// <exception cref="Tesla.Core.TeslaException">Thrown if creating the underlying implementation fails or the render
        /// system is not set.</exception>
        public override void Read(ISavableReader input) {
            IRenderSystemProvider renderSystem = input.RenderSystem;
            if(renderSystem == null) {
                Dispose();
                throw new TeslaException("Render system provider not set, cannot create graphics resource implementation.");
            }

            base.RenderSystem = renderSystem;

            String name = input.ReadString();
            SurfaceFormat format = input.ReadEnum<SurfaceFormat>();
            int width = input.ReadInt();
            int height = input.ReadInt();
            int depth = input.ReadInt();
            int mipCount = input.ReadInt();

            try {
                _impl = renderSystem.CreateTexture3DImplementation(width, height, depth, mipCount > 1, format, null);
                for(int i = 0; i < mipCount; i++) {
                    byte[] byteBuffer = input.ReadByteArray();
                    _impl.SetData<byte>(byteBuffer, i, 0, width, 0, height, 0, depth, 0, byteBuffer.Length);
                    width = System.Math.Max(width >> 1, 1);
                    height = System.Math.Max(height >> 1, 1);
                    depth = System.Math.Max(depth >> 1, 1);
                }
            } catch(Exception e) {
                Dispose();
                throw new TeslaException("Error creating underlying implementation, see inner exception for details.", e);
            }
        }
    }
}
